package dao.Impl;

import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BEncoderStream;
import dao.StaffsDao;
import entitl.Staffs;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.C3P0Util;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author czl
 * @Date 2024-03-12
 */
public class StaffsDaoDbutils implements StaffsDao {
    @Override
    public List<Staffs> selectAll() {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());

        String sql="select * from staffs";
        List<Staffs> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<>(Staffs.class));
        } catch (SQLException e) {
            System.out.println("编写查询数据失败！！！");
        }
        return list;
    }

    @Override
    public int delete(int id) {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource()) ;

        String sql="delete from staffs where id=?";

        try {
            qr.update(sql,id);
        } catch (SQLException e) {
            System.out.println("编写删除数据失败！！！");
        }

        return 0;
    }

    @Override
    public int insert(Staffs staffs) {
        return 0;
    }

    @Override
    public int update(Staffs staffs) {
        QueryRunner qr= new QueryRunner(C3P0Util.getDataSource());

        String sql="update staffs set name=?,age=?,phone=?,pos=?,update_time=? where id=?";

        try {
            qr.update(sql,staffs);
        } catch (SQLException e) {
            System.out.println("编写修改数据失败！！！");
        }

        return 0;
    }

    @Override
    public List<Staffs> selectByPage(int limit, int count) {

        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource()) ;

        String sql = "select id,name,age,phone,pos,add_time as addTime,update_time as updateTime from staffs limit ?,?";
        List<Staffs> list=null;
        try {
              list=qr.query(sql, new BeanListHandler<>(Staffs.class),limit,count);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
}
